<template>
  <div class="open-list">
    <el-card class="box-card">
      <!-- 头部 -->
      <div slot="header" class="clearfix fix-lh">
        <span>绑定列表 - <em style="font-size:12px;">用户账号{{$route.query.phone}}</em></span>
        <div class="btn-list">
          <el-button @click="handleRecord">操作记录</el-button>
          <el-button @click="goRefresh">刷新</el-button>
          <el-button @click="goBack">返回</el-button>
        </div>
      </div>
      <div class="home-body">
        <cvue-table :option="tableOption" :data="tableData" ref="tbl1" :isShowAdd="false" :page="page" :tablePage="tablePage" :pageSize="page.pageSize" :loading="tableLoading" @current-change="handleCurrentChange" @size-change="handleSizeChange" :isShowPage="pageShow">
          <template slot-scope="scope" slot="controlledId">
            <span>{{scope.row.controlledId}}</span>
          </template>
          <template slot-scope="scope" slot="state">
            <span>{{scope.row.state | stateFilter}}</span>
          </template>
          <template slot-scope="scope" slot="birthday">
            <span>{{scope.row.birthday | getBirth}}</span>
          </template>
          <template slot-scope="scope" slot="grade">
            <span>{{scope.row.grade ? scope.row.grade : '-'}}</span>
          </template>
            <el-table-column fixed="right" slot="actionMenu" label="操作" align="center" header-align="center" width="160">
            <template slot-scope="scope">
              <el-button v-if="hasPermission" type="text" size="small" @click="handleCancel(scope.row)" >解绑</el-button>
              <el-button type="text" size="small" @click="getCurrentStrategy(scope.row)" :disabled="!(scope.row.state == 1 && isVip)">当前策略</el-button>
            </template>
          </el-table-column>
        </cvue-table>
      </div>
    </el-card>
    <!-- 操作历史记录 -->
    <open-record @closeDialog="closeDialog('record')" @confirmDialog="confirmDialog('record')" @handleClose="closeDialog('record')" :dialogVisible="dialogVisibleRecord">
    </open-record>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import cvueTable from '@/components/cvue-table'
import cvueDialog from '@/components/cvue-dialog'
import kidMsg from './kidMsg'
import openListAdd from './openListAdd'
import openRecord from './openRecord'
import { baseUrl } from '@/config/config.js'
export default {
  name: 'openList',
  components: {
    cvueTable,
    cvueDialog,
    openListAdd,
    kidMsg,
    openRecord
  },
  data () {
    var checkPhone = (rule, value, callback) => {
      const reg = /^1[3456789]\d{9}$/
      if (!value) {
        callback(new Error('请输入手机号码'))
      } else if (!reg.test(value)) {
        callback(new Error('请输入正确的11位手机号码'))
      } else if (value == this.userName) {
        callback(new Error('该手机号为家长手机号，无法开通该业务'))
      } else {
        callback()
      }
    }
    return {
      isVip: false, // 会员状
      nextLoading: false,
      orderLoading: false,
      bindLoading: false,
      productList: [],
      showFirst: true,
      showSecond: false,
      showThird: false,
      showFourth: false,
      title: '新增',
      productId: '',
      productName: '',
      productDescribe: '',
      expireTime: '',
      subscriptionId: '',
      inureTime: '',
      homeCity: '',
      isCheck: '1',
      marketing: '1',
      ifmarketing: false, // 是否开通营销案
      notice: '',
      isChild: false, // 是否有查看孩子管理的权限
      hasPermission: false,
      keyword: '',
      tableLoading: false,
      dialogVisibleKid: false,
      dialogVisibleAdd: false,
      dialogVisibleSecond: false,
      dialogVisibleThird: false,
      dialogVisibleRecord: false,
      userName: '',
      userId: '',
      controlledId: '',
      pageShow: true,
      tablePage: 1,
      page: {
        total: 1, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10, // 每页显示多少条
        pageSizes: [10, 50, 100]
      },
      tableOption: {
        stripe: true,
        width: '100%',
        border: true,
        index: false,
        cloumn: [
          { prop: 'index', label: '序号', align: 'center', width: 80 },
          { prop: 'createTime', label: '绑定时间', align: 'center', minWidth: 180 },
          { prop: 'phoneMode', label: '设备名称', align: 'center', minWidth: 180 },
          { prop: 'state', label: '管控状态', align: 'center', minWidth: 80, slotStatus: true },
          { prop: 'nickName', label: '昵称', align: 'center', minWidth: 180 },
          { prop: 'sex', label: '性别', align: 'center', minWidth: 50 },
          { prop: 'birthday', label: '出生日期', align: 'center', minWidth: 120, slotStatus: true },
          { prop: 'grade', label: '年级', align: 'center', minWidth: 180, slotStatus: true},
          // { prop: 'controlledId', label: '孩子手机号', align: 'center', width: 150, slotStatus: true },
          // { prop: 'controlledName', label: '昵称', align: 'center' },
          // { prop: 'sex', label: '性别', align: 'center', width: 120, slotStatus: true },
          // { prop: 'isAllowed', label: '退订需家长同意', align: 'center', width: 120, slotStatus: true },
          // { prop: 'expireDate', label: '业务到期时间', align: 'center', minWidth: 180, slotStatus: true },
          // { prop: 'area', label: '所属地区', align: 'center', minWidth: 100, slotStatus: true }
        ]
      },
      tableData: [],
      ruleForm: { phone: '' },
      rules: { phone: [{ trigger: 'blur', validator: checkPhone }] },
      areaColumns: [
        { name: '福建省 - 福州市', code: '350100' },
        { name: '福建省 - 厦门市', code: '350200' },
        { name: '福建省 - 莆田市', code: '350300' },
        { name: '福建省 - 三明市', code: '350400' },
        { name: '福建省 - 泉州市', code: '350500' },
        { name: '福建省 - 漳州市', code: '350600' },
        { name: '福建省 - 南平市', code: '350700' },
        { name: '福建省 - 龙岩市', code: '350800' },
        { name: '福建省 - 宁德市', code: '350900' }
      ]
    }
  },
  filters: {
    stateFilter(value) {
      let str = ''
      if (value == 1) {
        str = '正常'
      }
      if (value == 0) {
        str = '脱管'
      }
      return str
    },
    getSex (value) {
      var sex = ''
      if (value == 1) {
        sex = '男'
      } else if (value == 0) {
        sex = '女'
      }
      return sex
    },
    getBirth (value) {
      if (value == '' || value == null) {
        return '-'
      } else {
        var obj = value.split('-')
        return obj[0] + '-' + obj[1] + '-' + obj[2]
      }
    }
  },
  mounted () {
    this.userName = this.$route.query.userName
    this.userId = this.$route.query.userId
    let vipState = this.$route.query.vipstate
    if (vipState == 1 || vipState == 3) {
      this.isVip = true
    }
    console.log('this.isVip', this.isVip)
    let permission = sessionStorage.getItem('permission')
    if (permission) {
      permission = JSON.parse(permission)
      permission.forEach(p => {
        if (p.code == '11000' && p.permissions.indexOf('edit') != -1) {
          this.hasPermission = true
        }
      })
    }
    this.handleList() // 获取列表详情
  },
  computed: {
    ...mapGetters(['permissionList', 'isCollapse',
      'menu',
      'keepAlive',
      'keepAlivePage',
      'keepAlivePath']),
    getPermisson () {
      var permisson = ''
      this.permissionList.forEach((item, index) => {
        if (item.code == 12010) {
          permisson = item.permissions
        }
      })
      return permisson.indexOf('edit') >= 0
    }
  },
  methods: {
    // 当前策略
    getCurrentStrategy (row) {
      console.log(row)
      this.goUrl('current-strategy', {
        id: row.id,
        nickname: row.nickName,
        userId: this.$route.query.userId,
        phone: this.$route.query.phone,
        vipstate: this.$route.query.vipstate
      })
    },
    closeDialog(params) {
      if (params == 'record') {
        this.dialogVisibleRecord = false
      }
    },
    // 改变页码
    handleCurrentChange (val) {
      this.tablePage = val
      this.handleList()
    },
    // 改变pagesize
    handleSizeChange (val) {
      this.tablePage = 1
      this.page.pageSize = val
      this.handleList()
    },
    // 列表接口
    handleList () {
      var params = {
        pageIndex: this.tablePage,
        pageSize: this.page.pageSize,
        userId: this.userId
        // status: '0' // 状态 0是正常的 1是退订
      }
      this.tableLoading = true
      this.$store.dispatch('commonUser/GetAccountList', params).then(res => {
        // console.log(res)
        if (res.code == 200) {
          var data = res.data
          this.tableData = data.list
          console.log(this.tableData)
          this.tableLoading = false
          if (this.tableData == '') {
            this.pageShow = false
          } else {
            this.pageShow = true
          }
        } else {
          this.$message({
            message: res.msg,
            duration: 2000,
            type: 'error'
          })
          this.tableLoading = false
        }
        this.page.total = data.total
        this.page.currentPage = this.tablePage
      }).catch(err => {
        console.log(err)
        this.tableLoading = false
      })
    },
    // 操作记录
    handleRecord () {
      this.dialogVisibleRecord = true
    },
    // 退订
    handleCancel (row) {
      console.log('handleCancel',row)
      let phone = this.$route.query.phone
      var text = '是否要将「' + row.nickName + '」从' + phone + '上进行解绑？'
      this.$confirm(text, '解绑', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            var params = {
              controlledId: parseInt(row.id),
              userId: parseInt(this.$route.query.userId),
              phone: this.$route.query.phone
            }
            // 进行退订操作
            this.$store.dispatch('commonUser/DeleteBusiness', params).then(res => {
              // console.log(res)
              if (res.code == 200) {
                this.$message({
                  type: 'success',
                  message: res.msg
                })
                done()
                setTimeout(() => {
                  instance.confirmButtonLoading = false
                }, 300)
                // instance.confirmButtonLoading = false
                this.keyword = ''
                this.tablePage = 1
                this.handleList()
              } else {
                this.$message({
                  type: 'error',
                  message: res.msg
                })
                done()
                instance.confirmButtonLoading = false
              }
            }).catch(err => {
              console.log('err', err)
              done()
            })
          } else {
            done()
          }
        }
      }).then(() => {
      }).catch(() => {
      })
    },
    // 刷新页面
    goRefresh () {
      this.handleList() // 获取列表详情
    },
    // 返回到家长管理
    goBack () {
      var path = '/user/index'
      var index = this.keepAlivePath.indexOf(path)
      console.log(index, this.activeIndex, path)
      this.closeTagTo('/user/index')
    }
  }
}
</script>
<style lang="scss">
.open-list {
  padding: 0px !important;
  height: auto !important;
  .home-body {
    margin-top: -15px;
  }
  .product-box {
    // padding: 10px;
    // .el-radio__inner::after {
    //   background-color: #409eff;
    // }
    // .el-radio__input.is-checked + .el-radio__label {
    //   color: #333;
    // }
    .product-gap-yxa {
      font-weight: 600;
    }
    .product-gap {
      margin-bottom: 20px;
    }
    .chiosetxt {
      display: inline-block;
      width: 10em;
    }
  }
  .notice {
    padding: 10px;
    text-align: center;
  }
  .btn-list {
    float: right;
  }
  .el-card__header {
    border-bottom: none;
  }
  .fix-lh {
    line-height: 32px;
  }
  .text-right {
    text-align: right;
  }
  .el-card__header,
  .el-card__body {
    padding: 15px;
  }
  .el-input.is-disabled .el-input__inner {
    color: #606266;
  }
  .el-dialog__footer {
    text-align: center !important;
  }
}
</style>
<style>
.open-list .el-card__header {
  border-bottom: none;
}
.open-list .el-card__header,
.el-card__body {
  padding: 15px;
}
.open-list .el-table__body tr td:nth-child(3) span {
  /* color: #409eff;
  cursor: pointer; */
}
.open-record .el-table__body tr td:nth-child(3) span {
  color: #606266;
  cursor: text;
}
</style>
